{% extends "base.html" %}

{% block title %}任务管理 - Alist-Sync{% endblock %}

{% block page_title %}同步任务管理{% endblock %}

{% block styles %}
<style>
    .task-row {
        cursor: pointer;
        transition: background-color 0.2s;
        position: relative;
    }
    
    .task-row:hover {
        background-color: rgba(255, 255, 255, 0.1) !important;
    }
    
    .task-row:hover:after {
        content: "点击查看详情";
        position: absolute;
        right: 150px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: #fff;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0.8;
    }
    
    .active-task-row {
        background-color: rgba(13, 110, 253, 0.2) !important;
    }
    
    .task-detail-row {
        background-color: rgba(0, 0, 0, 0.2);
    }
    
    .task-detail-row .card {
        border-left: 4px solid #0d6efd;
    }
    
    /* 添加展开指示器 */
    .task-row td:first-child::before {
        content: "▶";
        color: #6c757d;
        margin-right: 6px;
        display: inline-block;
        transition: transform 0.2s;
    }
    
    .active-task-row td:first-child::before {
        content: "▼";
        color: #0d6efd;
    }
</style>
{% endblock %}

{% block header_buttons %}
<!-- 移除重复的添加任务按钮 -->
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card bg-white shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">任务列表</h5>
                <div>
                    <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addTaskModal">
                        <i class="bi bi-plus-lg"></i> 新增任务
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0 task-list-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th class="task-name-column">任务名称</th>
                                <th>源连接</th>
                                <th>目标连接</th>
                                <th>同步模式</th>
                                <th>创建时间</th>
                                <th>上次运行</th>
                                <th>下次运行</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="tasks-table">
                            {% if tasks %}
                                {% for task in tasks %}
                                <tr class="task-row" data-task-id="{{ task.id }}">
                                    <td>{{ task.id }}</td>
                                    <td>{{ task.name }}</td>
                                    <td>{{ task.source_connection_name }}</td>
                                    <td>{{ task.target_connection_names }}</td>
                                    <td>
                                        {% if task.sync_type == 'file_sync' %}
                                        <span class="badge bg-info">文件同步</span>
                                        {% elif task.sync_type == 'file_move' %}
                                        <span class="badge bg-primary">文件移动</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ task.created_at }}</td>
                                    <td>{{ task.last_run or "从未" }}</td>
                                    <td>{{ task.next_run or "未计划" }}</td>
                                    <td>
                                        {% if task.status == 'running' %}
                                        <span class="badge bg-primary">运行中</span>
                                        {% elif task.status == 'completed' %}
                                        <span class="badge bg-success">已完成</span>
                                        {% elif task.status == 'failed' %}
                                        <span class="badge bg-danger">失败</span>
                                        {% elif task.status == 'pending' %}
                                        <span class="badge bg-secondary">等待中</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <button class="btn btn-sm btn-primary run-task" data-task-id="{{ task.id }}">
                                                <i class="bi bi-play-fill"></i>
                                            </button>
                                            <button class="btn btn-sm btn-info edit-task" data-task-id="{{ task.id }}">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger delete-task" data-task-id="{{ task.id }}">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                            <button class="btn btn-sm btn-secondary view-instances" data-task-id="{{ task.id }}" data-task-name="{{ task.name }}">
                                                <i class="bi bi-list-ul"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr class="task-detail-row" id="task-detail-{{ task.id }}" style="display: none;">
                                    <td colspan="10">
                                        <div class="card tech-card mb-0">
                                            <div class="card-body">
                                                <h5 class="card-title">任务详情</h5>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-2">
                                                            <strong>源路径:</strong> {{ task.source_path }}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>目标路径:</strong> {{ task.target_path }}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>同步模式:</strong> 
                                                            {% if task.sync_type == 'file_sync' %}文件同步
                                                            {% elif task.sync_type == 'file_move' %}文件移动
                                                            {% endif %}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>差异项处理:</strong> 
                                                            {% if task.sync_diff_action == 'none' %}不处理
                                                            {% elif task.sync_diff_action == 'move' %}移至回收站
                                                            {% elif task.sync_diff_action == 'delete' %}删除
                                                            {% endif %}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>排除目录:</strong> {{ task.exclude_dirs or "无" }}
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-2">
                                                            <strong>计划:</strong> {{ task.schedule or "手动执行" }}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>文件过滤:</strong> {{ task.file_filter or "无" }}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>启用状态:</strong> {{ "启用" if task.enabled else "禁用" }}
                                                        </div>
                                                        <div class="mb-2">
                                                            <strong>目标存储数量:</strong> 
                                                            {% if task.target_connection_ids and task.target_connection_ids|length > 0 %}
                                                                {{ task.target_connection_ids|length }}
                                                            {% else %}
                                                                1
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            {% else %}
                                <tr>
                                    <td colspan="10" class="text-center">暂无任务</td>
                                </tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加任务模态框 -->
<div class="modal fade" id="addTaskModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加同步任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="addTaskModalMessages"></div>
                <form id="taskForm">
                    <div class="mb-3">
                        <label for="taskName" class="form-label">任务名称</label>
                        <input type="text" class="form-control" id="taskName" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="connectionSelector" class="form-label">选择连接器</label>
                        <select class="form-select" id="connectionSelector" required>
                            <option value="">选择连接器</option>
                            <!-- 通过JavaScript动态添加连接选项 -->
                        </select>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="sourceConnection" class="form-label">源连接</label>
                            <select class="form-select" id="sourceConnection" required>
                                <option value="">选择源连接</option>
                                <!-- 根据选择的连接器动态加载存储列表 -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="targetConnections" class="form-label">目标连接</label>
                            <select class="form-select" id="targetConnections" multiple required>
                                <!-- 目标连接为多选 -->
                            </select>
                            <div class="form-text">按住Ctrl键可多选</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="sourcePath" class="form-label">源路径</label>
                            <input type="text" class="form-control" id="sourcePath" placeholder="/" required>
                        </div>
                        <div class="col-md-6">
                            <label for="targetPath" class="form-label">目标路径</label>
                            <input type="text" class="form-control" id="targetPath" placeholder="/" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="excludeDirs" class="form-label">排除目录</label>
                        <input type="text" class="form-control" id="excludeDirs" placeholder="/">
                        <div class="form-text">相对于源路径，多个目录用英文逗号分隔</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="syncType" class="form-label">同步模式</label>
                        <select class="form-select" id="syncType" required>
                            <option value="file_sync">文件同步</option>
                            <option value="file_move">文件移动</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="syncDiffAction" class="form-label">差异项处理策略</label>
                        <select class="form-select" id="syncDiffAction">
                            <option value="none">不处理目标目录差异项</option>
                            <option value="move">移至目标目录回收站</option>
                            <option value="delete">删除目标目录多余项</option>
                        </select>
                        <div class="form-text">注意：选择"文件移动"模式时，差异项处理策略将被禁用</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="schedule" class="form-label">计划 (Cron 表达式，留空表示手动)</label>
                        <input type="text" class="form-control" id="schedule" placeholder="*/30 * * * *">
                        <div class="form-text">示例：*/30 * * * * (每30分钟)</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="fileFilter" class="form-label">文件过滤 (正则表达式，留空表示无过滤)</label>
                        <input type="text" class="form-control" id="fileFilter" placeholder="\.jpg$|\.png$">
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="sizeMin" class="form-label">最小文件大小 (字节, 可选)</label>
                            <input type="number" class="form-control" id="sizeMin" min="0" placeholder="仅传输大于此大小的文件">
                        </div>
                        <div class="col-md-6">
                            <label for="sizeMax" class="form-label">最大文件大小 (字节, 可选)</label>
                            <input type="number" class="form-control" id="sizeMax" min="0" placeholder="仅传输小于此大小的文件">
                        </div>
                    </div>
                    
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="taskEnabled" checked>
                        <label class="form-check-label" for="taskEnabled">启用任务</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveTaskBtn">保存任务</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑任务模态框 -->
<div class="modal fade" id="editTaskModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑同步任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="editTaskModalMessages"></div>
                <form id="editTaskForm">
                    <input type="hidden" id="editTaskId">
                    <div class="mb-3">
                        <label for="editTaskName" class="form-label">任务名称</label>
                        <input type="text" class="form-control" id="editTaskName" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editConnectionSelector" class="form-label">选择连接器</label>
                        <select class="form-select" id="editConnectionSelector" required>
                            <option value="">选择连接器</option>
                            <!-- 通过JavaScript动态添加连接选项 -->
                        </select>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="editSourceConnection" class="form-label">源连接</label>
                            <select class="form-select" id="editSourceConnection" required>
                                <option value="">选择源连接</option>
                                <!-- 根据选择的连接器动态加载存储列表 -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="editTargetConnections" class="form-label">目标连接</label>
                            <select class="form-select" id="editTargetConnections" multiple required>
                                <!-- 目标连接为多选 -->
                            </select>
                            <div class="form-text">按住Ctrl键可多选</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="editSourcePath" class="form-label">源路径</label>
                            <input type="text" class="form-control" id="editSourcePath" placeholder="/" required>
                        </div>
                        <div class="col-md-6">
                            <label for="editTargetPath" class="form-label">目标路径</label>
                            <input type="text" class="form-control" id="editTargetPath" placeholder="/" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editExcludeDirs" class="form-label">排除目录</label>
                        <input type="text" class="form-control" id="editExcludeDirs" placeholder="/">
                        <div class="form-text">相对于源路径，多个目录用英文逗号分隔</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editSyncType" class="form-label">同步模式</label>
                        <select class="form-select" id="editSyncType" required>
                            <option value="file_sync">文件同步</option>
                            <option value="file_move">文件移动</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editSyncDiffAction" class="form-label">差异项处理策略</label>
                        <select class="form-select" id="editSyncDiffAction">
                            <option value="none">不处理目标目录差异项</option>
                            <option value="move">移至目标目录回收站</option>
                            <option value="delete">删除目标目录多余项</option>
                        </select>
                        <div class="form-text">注意：选择"文件移动"模式时，差异项处理策略将被禁用</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editSchedule" class="form-label">计划 (Cron 表达式，留空表示手动)</label>
                        <input type="text" class="form-control" id="editSchedule" placeholder="*/30 * * * *">
                        <div class="form-text">示例：*/30 * * * * (每30分钟)</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editFileFilter" class="form-label">文件过滤 (正则表达式，留空表示无过滤)</label>
                        <input type="text" class="form-control" id="editFileFilter" placeholder="\.jpg$|\.png$">
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="editSizeMin" class="form-label">最小文件大小 (字节, 可选)</label>
                            <input type="number" class="form-control" id="editSizeMin" min="0" placeholder="仅传输大于此大小的文件">
                        </div>
                        <div class="col-md-6">
                            <label for="editSizeMax" class="form-label">最大文件大小 (字节, 可选)</label>
                            <input type="number" class="form-control" id="editSizeMax" min="0" placeholder="仅传输小于此大小的文件">
                        </div>
                    </div>
                    
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="editTaskEnabled" checked>
                        <label class="form-check-label" for="editTaskEnabled">启用任务</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="updateTaskBtn">更新任务</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除此任务吗？该操作不可恢复。</p>
                <input type="hidden" id="deleteTaskId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 任务实例列表模态框 -->
<div class="modal fade" id="taskInstancesModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">任务实例列表</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h6 id="instancesTaskName" class="mb-3"></h6>
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>开始时间</th>
                                <th>结束时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="instances-table">
                            <tr>
                                <td colspan="5" class="text-center">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 任务日志查看模态框 -->
<div class="modal fade" id="taskLogModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">任务执行日志</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h6 id="logTaskName" class="mb-3"></h6>
                <div id="logContent" class="bg-light p-3 rounded" style="max-height: 500px; overflow-y: auto; white-space: pre-wrap;">
                    <pre id="task-log-content" class="mb-0" style="white-space: pre-wrap;"></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="refreshLogBtn">刷新</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('页面加载完成，开始初始化...');
        
        // 全局变量，用于存储连接数据
        let globalConnections = [];
        
        // 加载所有连接
        loadConnections();
        
        // 加载任务列表
        console.log('开始加载任务列表...');
        loadTasks();
        
        // 为已存在的任务行添加事件
        console.log('为当前任务行添加事件...');
        attachTaskRowEvents();
        
        // 初始绑定删除确认按钮事件
        document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
            const taskId = document.getElementById('deleteTaskId').value;
            deleteTask(taskId, this);
        });
        
        // 延迟检查任务行事件绑定
        setTimeout(function() {
            console.log('延迟检查任务行事件绑定...');
            const taskRows = document.querySelectorAll('.task-row');
            if (taskRows.length > 0) {
                console.log(`检测到 ${taskRows.length} 个任务行，重新绑定事件`);
                
                // 添加直接的点击处理
                taskRows.forEach(row => {
                    // 移除旧事件，防止重复
                    row.removeEventListener('click', taskRowClickHandler);
                    // 添加新事件
                    row.addEventListener('click', taskRowClickHandler);
                    console.log('已为任务行重新绑定点击事件:', row.getAttribute('data-task-id'));
                });
            } else {
                console.log('未检测到任务行，可能加载有延迟');
            }
        }, 1000); // 等待1秒
        
        // 定义任务行点击处理函数
        function taskRowClickHandler(event) {
            console.log('任务行点击处理函数被调用');
            
            // 如果点击的是按钮，不处理展开/收起
            if (event.target.tagName === 'BUTTON' || 
                event.target.closest('button') || 
                event.target.tagName === 'I' ||
                event.target.closest('.btn-group')) {
                console.log('点击了按钮区域，忽略展开/收起');
                return;
            }
            
            // 获取任务ID
            const taskId = this.getAttribute('data-task-id');
            console.log('点击任务行:', taskId);
            const detailRow = document.getElementById(`task-detail-${taskId}`);
            
            if (!detailRow) {
                console.error(`找不到详情行 task-detail-${taskId}`);
                return;
            }
            
            // 切换详情行的显示状态
            if (detailRow.style.display === 'none' || !detailRow.style.display) {
                // 关闭其他打开的详情行
                document.querySelectorAll('.task-detail-row').forEach(row => {
                    if (row.id !== `task-detail-${taskId}`) {
                        row.style.display = 'none';
                        // 移除其他行的活动类
                        const otherId = row.id.replace('task-detail-', '');
                        const otherRow = document.querySelector(`.task-row[data-task-id="${otherId}"]`);
                        if (otherRow) otherRow.classList.remove('active-task-row');
                    }
                });
                
                // 显示当前详情行
                detailRow.style.display = 'table-row';
                this.classList.add('active-task-row');
            } else {
                // 隐藏当前详情行
                detailRow.style.display = 'none';
                this.classList.remove('active-task-row');
            }
        }
        
        // 初始化检查同步模式，如有必要则禁用差异项处理策略
        function initSyncTypeHandling() {
            // 检查添加任务表单
            const syncType = document.getElementById('syncType');
            if (syncType.value === 'file_move') {
                const syncDiffAction = document.getElementById('syncDiffAction');
                syncDiffAction.value = 'none';
                syncDiffAction.disabled = true;
                syncDiffAction.parentElement.querySelector('.form-text').textContent = '注意："文件移动"模式下，差异项处理策略已被禁用';
            }
            
            // 检查编辑任务表单
            const editSyncType = document.getElementById('editSyncType');
            if (editSyncType.value === 'file_move') {
                const editSyncDiffAction = document.getElementById('editSyncDiffAction');
                editSyncDiffAction.value = 'none';
                editSyncDiffAction.disabled = true;
                editSyncDiffAction.parentElement.querySelector('.form-text').textContent = '注意："文件移动"模式下，差异项处理策略已被禁用';
            }
        }
        
        // 初始检查
        initSyncTypeHandling();
        
        // 监听模态框打开事件，确保状态正确
        document.getElementById('addTaskModal').addEventListener('show.bs.modal', initSyncTypeHandling);
        document.getElementById('editTaskModal').addEventListener('show.bs.modal', initSyncTypeHandling);
        
        // 连接选择器变更事件
        document.getElementById('connectionSelector').addEventListener('change', function() {
            const connId = this.value;
            if (connId) {
                loadStorages(connId);
            } else {
                // 清空存储列表
                document.getElementById('sourceConnection').innerHTML = '<option value="">选择源连接</option>';
                document.getElementById('targetConnections').innerHTML = '';
            }
        });
        
        // 编辑模式连接选择器变更事件
        document.getElementById('editConnectionSelector').addEventListener('change', function() {
            const connId = this.value;
            if (connId) {
                loadStoragesForEdit(connId);
            } else {
                // 清空存储列表
                document.getElementById('editSourceConnection').innerHTML = '<option value="">选择源连接</option>';
                document.getElementById('editTargetConnections').innerHTML = '';
            }
        });
        
        // 查看任务实例按钮
        document.querySelectorAll('.view-instances').forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.getAttribute('data-task-id');
                const taskName = this.getAttribute('data-task-name');
                
                // 显示任务名称
                document.getElementById('instancesTaskName').textContent = `任务: ${taskName} (ID: ${taskId})`;
                
                // 加载任务实例列表
                loadTaskInstances(taskId);
                
                // 显示模态框
                new bootstrap.Modal(document.getElementById('taskInstancesModal')).show();
            });
        });
        
        // 任务日志刷新按钮
        document.getElementById('refreshLogBtn').addEventListener('click', function() {
            const instanceId = this.getAttribute('data-instance-id');
            if (instanceId) {
                loadTaskLog(instanceId);
            }
        });
        
        // 编辑表单中的同步模式变更逻辑
        document.getElementById('editSyncType').addEventListener('change', function() {
            const editSyncDiffAction = document.getElementById('editSyncDiffAction');
            if (this.value === 'file_move') {
                editSyncDiffAction.value = 'none';
                editSyncDiffAction.disabled = true;
                editSyncDiffAction.parentElement.querySelector('.form-text').textContent = '注意："文件移动"模式下，差异项处理策略已被禁用';
            } else {
                editSyncDiffAction.disabled = false;
                editSyncDiffAction.parentElement.querySelector('.form-text').textContent = '注意：选择"文件移动"模式时，差异项处理策略将被禁用';
            }
        });
        
        // 添加任务表单中的同步模式变更逻辑
        document.getElementById('syncType').addEventListener('change', function() {
            const syncDiffAction = document.getElementById('syncDiffAction');
            if (this.value === 'file_move') {
                syncDiffAction.value = 'none';
                syncDiffAction.disabled = true;
                syncDiffAction.parentElement.querySelector('.form-text').textContent = '注意："文件移动"模式下，差异项处理策略已被禁用';
            } else {
                syncDiffAction.disabled = false;
                syncDiffAction.parentElement.querySelector('.form-text').textContent = '注意：选择"文件移动"模式时，差异项处理策略将被禁用';
            }
        });
        
        // 保存任务按钮
        document.getElementById('saveTaskBtn').addEventListener('click', function() {
            console.log('保存任务按钮被点击');
            
            // 验证必填字段
            const taskName = document.getElementById('taskName');
            if (!taskName.value.trim()) {
                showAddTaskMessage('请输入任务名称', 'warning');
                taskName.focus();
                console.log('验证失败：任务名称为空');
                return;
            }
            
            // 获取选择的源连接和目标连接
            const sourceConn = document.getElementById('sourceConnection');
            const targetConns = [];
            document.querySelectorAll('#targetConnections option:checked').forEach(option => {
                targetConns.push(option.value);
            });
            
            if (!sourceConn.value) {
                showAddTaskMessage('请选择源连接', 'warning');
                sourceConn.focus();
                console.log('验证失败：未选择源连接');
                return;
            }
            
            if (targetConns.length === 0) {
                showAddTaskMessage('请至少选择一个目标连接', 'warning');
                document.getElementById('targetConnections').focus();
                console.log('验证失败：未选择目标连接');
                return;
            }
            
            // 禁用按钮，显示加载状态
            this.disabled = true;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
            console.log('按钮已禁用，显示加载状态');
            
            // 准备表单数据
            const taskData = {
                name: taskName.value,
                connection_id: document.getElementById('connectionSelector').value || 1,
                source_connection_id: sourceConn.value,
                source_connection_name: sourceConn.options[sourceConn.selectedIndex].text,
                target_connection_ids: targetConns,
                target_connection_names: Array.from(document.querySelectorAll('#targetConnections option:checked')).map(opt => opt.text).join(', '),
                source_path: document.getElementById('sourcePath').value,
                target_path: document.getElementById('targetPath').value,
                exclude_dirs: document.getElementById('excludeDirs').value,
                sync_type: document.getElementById('syncType').value,
                sync_diff_action: document.getElementById('syncDiffAction').value,
                schedule: document.getElementById('schedule').value,
                file_filter: document.getElementById('fileFilter').value,
                size_min: document.getElementById('sizeMin').value ? parseInt(document.getElementById('sizeMin').value) : null,
                size_max: document.getElementById('sizeMax').value ? parseInt(document.getElementById('sizeMax').value) : null,
                enabled: document.getElementById('taskEnabled').checked
            };
            
            console.log('准备保存任务数据:', taskData);
            
            // 如果没有选择连接器，自动使用第一个连接ID
            if (!taskData.connection_id && globalConnections && globalConnections.length > 0) {
                taskData.connection_id = globalConnections[0].connection_id;
                console.log('未选择连接器，自动使用第一个连接ID:', taskData.connection_id);
            }
            
            // 发送AJAX请求保存任务
            console.log('开始发送AJAX请求');
            fetch('/api/tasks', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(taskData),
            })
            .then(response => {
                console.log('收到AJAX响应:', response.status, response.statusText);
                if (!response.ok) {
                    throw new Error(`网络响应错误: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('解析响应数据:', data);
                if (data.status === 'success') {
                    showAlert('任务添加成功', 'success');
                    // 关闭模态框 - 使用Bootstrap 5的方式关闭
                    const modalElement = document.getElementById('addTaskModal');
                    console.log('获取到模态框元素:', modalElement);
                    
                    try {
                        const bsModal = bootstrap.Modal.getOrCreateInstance(modalElement);
                        console.log('使用getOrCreateInstance获取模态框实例:', bsModal);
                        bsModal.hide();
                        console.log('模态框已关闭');
                    } catch (modalError) {
                        console.error('关闭模态框时出错:', modalError);
                    }
                    // 刷新任务列表而不是整个页面
                    loadTasks();
                    
                    // 重新加载调度器以更新任务计划
                    setTimeout(() => {
                        fetch('/api/scheduler/reload', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(result => {
                            console.log('调度器已重载:', result);
                            // 在调度器重载后再次刷新，确保下次运行时间更新
                            setTimeout(() => {
                                loadTasks();
                            }, 1000);
                        })
                        .catch(err => {
                            console.error('调度器重载失败:', err);
                        });
                    }, 500);
                } else {
                    throw new Error(data.message || '保存失败');
                }
            })
            .catch(error => {
                console.error('保存任务失败:', error);
                showAlert('保存任务失败: ' + error.message, 'danger');
                
                // 在控制台显示更多错误信息
                console.log('请检查控制台完整错误信息和网络请求');
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = '保存任务';
                console.log('按钮状态已恢复');
            });
        });
        
        // 编辑任务按钮
        document.querySelectorAll('.edit-task').forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.getAttribute('data-task-id');
                
                // 显示加载状态
                this.disabled = true;
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                
                // 通过API获取任务信息
                fetch(`/api/tasks/${taskId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取任务信息失败');
                    }
                    return response.json();
                })
                .then(task => {
                    // 调试输出任务数据
                    console.log('获取到的任务数据:', task);
                    
                    // 填充表单
                    document.getElementById('editTaskId').value = task.id;
                    document.getElementById('editTaskName').value = task.name;
                    
                    // 对于连接器，需要获取具体的连接ID
                    // 在task.json中通常没有直接保存connection_id，需要从源连接信息中提取
                    
                    // 设置源路径和目标路径
                    document.getElementById('editSourcePath').value = task.source_path || '/';
                    document.getElementById('editTargetPath').value = task.target_path || '/';
                    document.getElementById('editSyncType').value = task.sync_type || 'file_sync';
                    document.getElementById('editSyncDiffAction').value = task.sync_diff_action || 'none';
                    document.getElementById('editSchedule').value = task.schedule || '';
                    document.getElementById('editFileFilter').value = task.file_filter || '';
                    // 新增：最小/最大文件大小
                    document.getElementById('editSizeMin').value = task.size_min != null ? task.size_min : '';
                    document.getElementById('editSizeMax').value = task.size_max != null ? task.size_max : '';
                    document.getElementById('editExcludeDirs').value = task.exclude_dirs || '';
                    document.getElementById('editTaskEnabled').checked = task.enabled !== false;
                    
                    // 先加载所有连接，然后选择任务使用的连接并加载存储列表
                    loadConnectionsForEdit(task);
                    
                    // 显示编辑模态框
                    new bootstrap.Modal(document.getElementById('editTaskModal')).show();
                })
                .catch(error => {
                    console.error('获取任务信息失败:', error);
                    showAlert('获取任务信息失败: ' + error.message, 'danger');
                })
                .finally(() => {
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = originalHTML;
                });
            });
        });
        
        // 更新任务按钮
        document.getElementById('updateTaskBtn').addEventListener('click', function() {
            // 验证必填字段
            const editTaskName = document.getElementById('editTaskName');
            if (!editTaskName.value.trim()) {
                showEditMessage('请输入任务名称', 'warning');
                editTaskName.focus();
                return;
            }
            
            // 获取任务ID
            const taskId = document.getElementById('editTaskId').value;
            
            // 禁用按钮，显示加载状态
            this.disabled = true;
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 更新中...';
            
            // 获取选择的源连接和目标连接
            const sourceConn = document.getElementById('editSourceConnection');
            const targetConns = [];
            document.querySelectorAll('#editTargetConnections option:checked').forEach(option => {
                targetConns.push(option.value);
            });
            
            if (!sourceConn.value) {
                showEditMessage('请选择源连接', 'warning');
                sourceConn.focus();
                return;
            }
            
            if (targetConns.length === 0) {
                showEditMessage('请至少选择一个目标连接', 'warning');
                document.getElementById('editTargetConnections').focus();
                return;
            }
            
            // 准备表单数据
            const taskData = {
                name: editTaskName.value,
                connection_id: document.getElementById('editConnectionSelector').value || 1,
                source_connection_id: sourceConn.value,
                source_connection_name: sourceConn.options[sourceConn.selectedIndex].text,
                target_connection_ids: targetConns,
                target_connection_names: Array.from(document.querySelectorAll('#editTargetConnections option:checked')).map(opt => opt.text).join(', '),
                source_path: document.getElementById('editSourcePath').value,
                target_path: document.getElementById('editTargetPath').value,
                exclude_dirs: document.getElementById('editExcludeDirs').value,
                sync_type: document.getElementById('editSyncType').value,
                sync_diff_action: document.getElementById('editSyncDiffAction').value,
                schedule: document.getElementById('editSchedule').value,
                file_filter: document.getElementById('editFileFilter').value,
                size_min: document.getElementById('editSizeMin').value ? parseInt(document.getElementById('editSizeMin').value) : null,
                size_max: document.getElementById('editSizeMax').value ? parseInt(document.getElementById('editSizeMax').value) : null,
                enabled: document.getElementById('editTaskEnabled').checked
            };
            
            console.log('准备更新任务数据:', taskData);
            
            // 如果没有选择连接器，自动使用第一个连接ID
            if (!taskData.connection_id && globalConnections && globalConnections.length > 0) {
                taskData.connection_id = globalConnections[0].connection_id;
                console.log('未选择连接器，自动使用第一个连接ID:', taskData.connection_id);
            }
            
            // 发送AJAX请求更新任务
            fetch(`/api/tasks/${taskId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(taskData),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    showAlert(taskId ? '任务更新成功' : '任务创建成功', 'success');
                    // 关闭模态框并刷新任务列表
                    const modalElement = document.getElementById('editTaskModal');
                    console.log('获取到编辑模态框元素:', modalElement);
                    
                    try {
                        const bsModal = bootstrap.Modal.getOrCreateInstance(modalElement);
                        console.log('使用getOrCreateInstance获取编辑模态框实例:', bsModal);
                        bsModal.hide();
                        console.log('编辑模态框已关闭');
                    } catch (modalError) {
                        console.error('关闭编辑模态框时出错:', modalError);
                    }
                    loadTasks();
                    
                    // 重新加载调度器以更新任务计划
                    setTimeout(() => {
                        fetch('/api/scheduler/reload', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(result => {
                            console.log('调度器已重载:', result);
                            // 在调度器重载后再次刷新，确保下次运行时间更新
                            setTimeout(() => {
                                loadTasks();
                            }, 1000);
                        })
                        .catch(err => {
                            console.error('调度器重载失败:', err);
                        });
                    }, 500);
                } else {
                    showAlert(data.message || '保存任务失败', 'danger');
                }
            })
            .catch(error => {
                console.error('更新任务失败:', error);
                showAlert('更新任务失败: ' + error.message, 'danger');
            })
            .finally(() => {
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = originalHTML;
            });
        });
        
        // 删除按钮事件
        document.querySelectorAll('.delete-task').forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.getAttribute('data-task-id');
                document.getElementById('deleteTaskId').value = taskId;
                
                // 重新绑定确认删除按钮的事件处理函数
                const confirmBtn = document.getElementById('confirmDeleteBtn');
                // 移除之前可能存在的事件监听器
                const newConfirmBtn = confirmBtn.cloneNode(true);
                confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
                
                // 为新按钮添加事件监听器
                newConfirmBtn.addEventListener('click', function() {
                    deleteTask(taskId, this);
                });
                
                new bootstrap.Modal(document.getElementById('confirmDeleteModal')).show();
            });
        });
        
        // 运行任务按钮
        document.querySelectorAll('.run-task').forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.getAttribute('data-task-id');
                
                // 显示加载状态
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                this.disabled = true;
                
                // 发送AJAX请求运行任务
                fetch(`/api/tasks/${taskId}/run`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'success') {
                        // 显示任务运行结果
                        if (data.instance_id) {
                            // 如果返回了实例ID，提示查看日志
                            const result = confirm(`任务 ${taskId} 已开始运行，是否查看执行日志？`);
                            if (result) {
                                // 显示任务名称
                                const taskName = this.closest('tr').querySelector('td:nth-child(2)').textContent;
                                document.getElementById('logTaskName').textContent = `任务: ${taskName} (实例 ID: ${data.instance_id})`;
                                
                                // 设置刷新按钮的实例ID
                                document.getElementById('refreshLogBtn').setAttribute('data-instance-id', data.instance_id);
                                
                                // 加载任务日志
                                loadTaskLog(data.instance_id);
                                
                                // 显示日志模态框
                                new bootstrap.Modal(document.getElementById('taskLogModal')).show();
                            }
                        } else {
                            showAlert(`任务 ${taskId} 已开始运行`, 'success');
                        }
                        // 刷新任务列表而不是整个页面
                        loadTasks();
                        
                        // 重新加载调度器以更新任务计划
                        setTimeout(() => {
                            fetch('/api/scheduler/reload', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            })
                            .then(response => response.json())
                            .then(result => {
                                console.log('调度器已重载:', result);
                                // 在调度器重载后再次刷新，确保下次运行时间更新
                                setTimeout(() => {
                                    loadTasks();
                                }, 1000);
                            })
                            .catch(err => {
                                console.error('调度器重载失败:', err);
                            });
                        }, 500);
                    } else {
                        throw new Error(data.message || '运行失败');
                    }
                })
                .catch(error => {
                    console.error('运行任务失败:', error);
                    showAlert('运行任务失败: ' + error.message, 'danger');
                })
                .finally(() => {
                    // 恢复按钮状态
                    this.innerHTML = originalHTML;
                    this.disabled = false;
                });
            });
        });
        
        // 辅助函数：加载所有连接
        function loadConnections() {
            fetch('/api/connections')
            .then(response => response.json())
            .then(connections => {
                // 存储连接数据到全局变量
                globalConnections = connections;
                
                const connectionSelector = document.getElementById('connectionSelector');
                connectionSelector.innerHTML = '<option value="">选择连接器</option>';
                
                if (connections && connections.length > 0) {
                    connections.forEach(conn => {
                        const option = document.createElement('option');
                        option.value = conn.connection_id;
                        option.textContent = conn.name;
                        connectionSelector.appendChild(option);
                    });
                }
            })
            .catch(error => {
                console.error('加载连接失败:', error);
                showAlert('加载连接列表失败', 'danger');
            });
        }
        
        // 辅助函数：加载编辑模式的连接
        function loadConnectionsForEdit(task) {
            fetch('/api/connections')
            .then(response => response.json())
            .then(connections => {
                const editConnectionSelector = document.getElementById('editConnectionSelector');
                editConnectionSelector.innerHTML = '<option value="">选择连接器</option>';
                
                if (connections && connections.length > 0) {
                    connections.forEach(conn => {
                        const option = document.createElement('option');
                        option.value = conn.connection_id;
                        option.textContent = conn.name;
                        editConnectionSelector.appendChild(option);
                    });
                    
                    // 使用任务中的连接ID填充编辑表单
                    // 通常，任务中都应该有这个连接器ID
                    const connId = task.connection_id || task.conn_id;
                    
                    // 打印任务数据，帮助调试
                    console.log('任务数据:', task);
                    
                    if (connId) {
                        // 设置选中的连接器
                        editConnectionSelector.value = connId;
                        // 加载连接器的存储列表
                        loadStoragesForEdit(connId, task);
                    } else {
                        console.warn('任务数据中没有找到connection_id字段');
                        // 尝试从第一个连接加载存储列表
                        if (connections.length > 0) {
                            const firstConnId = connections[0].connection_id;
                            editConnectionSelector.value = firstConnId;
                            loadStoragesForEdit(firstConnId, task);
                        }
                    }
                }
            })
            .catch(error => {
                console.error('加载连接失败:', error);
                showAlert('加载连接列表失败', 'danger');
            });
        }
        
        // 辅助函数：加载存储列表
        function loadStorages(connId) {
            // 显示加载中状态
            document.getElementById('sourceConnection').innerHTML = '<option value="">加载中...</option>';
            document.getElementById('targetConnections').innerHTML = '<option value="">加载中...</option>';
            
            fetch(`/api/storages?conn_id=${connId}`)
            .then(response => response.json())
            .then(data => {
                const sourceConnection = document.getElementById('sourceConnection');
                const targetConnections = document.getElementById('targetConnections');
                
                // 重置选择器
                sourceConnection.innerHTML = '<option value="">选择源连接</option>';
                targetConnections.innerHTML = '';
                
                if (data.status === 'success' && data.data && data.data.length > 0) {
                    // 填充存储列表
                    data.data.forEach(storage => {
                        // 添加到源连接
                        const sourceOption = document.createElement('option');
                        sourceOption.value = storage.id || storage.name;
                        sourceOption.textContent = storage.name;
                        sourceConnection.appendChild(sourceOption);
                        
                        // 添加到目标连接
                        const targetOption = document.createElement('option');
                        targetOption.value = storage.id || storage.name;
                        targetOption.textContent = storage.name;
                        targetConnections.appendChild(targetOption);
                    });
                } else {
                    showAlert('获取存储列表失败或存储列表为空', 'warning');
                }
            })
            .catch(error => {
                console.error('加载存储列表失败:', error);
                showAlert('加载存储列表失败: ' + error.message, 'danger');
                
                // 重置选择器
                document.getElementById('sourceConnection').innerHTML = '<option value="">选择源连接</option>';
                document.getElementById('targetConnections').innerHTML = '';
            });
        }
        
        // 辅助函数：加载编辑模式的存储列表
        function loadStoragesForEdit(connId, task = null) {
            // 显示加载中状态
            document.getElementById('editSourceConnection').innerHTML = '<option value="">加载中...</option>';
            document.getElementById('editTargetConnections').innerHTML = '<option value="">加载中...</option>';
            
            fetch(`/api/storages?conn_id=${connId}`)
            .then(response => response.json())
            .then(data => {
                const editSourceConnection = document.getElementById('editSourceConnection');
                const editTargetConnections = document.getElementById('editTargetConnections');
                
                // 重置选择器
                editSourceConnection.innerHTML = '<option value="">选择源连接</option>';
                editTargetConnections.innerHTML = '';
                
                if (data.status === 'success' && data.data && data.data.length > 0) {
                    // 填充存储列表
                    data.data.forEach(storage => {
                        // 添加到源连接
                        const sourceOption = document.createElement('option');
                        sourceOption.value = storage.id || storage.name;
                        sourceOption.textContent = storage.name;
                        editSourceConnection.appendChild(sourceOption);
                        
                        // 添加到目标连接
                        const targetOption = document.createElement('option');
                        targetOption.value = storage.id || storage.name;
                        targetOption.textContent = storage.name;
                        editTargetConnections.appendChild(targetOption);
                    });
                    
                    // 如果有任务数据，设置选中的值
                    if (task) {
                        console.log('正在填充源连接和目标连接:', task);
                        
                        // 设置源连接
                        if (task.source_connection_id) {
                            console.log('设置源连接:', task.source_connection_id);
                            editSourceConnection.value = task.source_connection_id;
                        }
                        
                        // 设置目标连接（多选）
                        if (task.target_connection_ids && Array.isArray(task.target_connection_ids)) {
                            console.log('设置目标连接:', task.target_connection_ids);
                            // 由于是select multiple，需要逐个设置option的selected属性
                            Array.from(editTargetConnections.options).forEach(option => {
                                option.selected = task.target_connection_ids.includes(option.value);
                            });
                        }
                    }
                } else {
                    console.error('获取存储列表失败或为空:', data);
                    showAlert('获取存储列表失败或存储列表为空', 'warning');
                }
            })
            .catch(error => {
                console.error('加载存储列表失败:', error);
                showAlert('加载存储列表失败: ' + error.message, 'danger');
                
                // 重置选择器
                document.getElementById('editSourceConnection').innerHTML = '<option value="">选择源连接</option>';
                document.getElementById('editTargetConnections').innerHTML = '';
            });
        }
        
        // 辅助函数：加载任务实例列表
        function loadTaskInstances(taskId) {
            const instancesTable = document.getElementById('instances-table');
            instancesTable.innerHTML = '<tr><td colspan="5" class="text-center">加载中...</td></tr>';
            
            fetch(`/api/task-instances?task_id=${taskId}`)
            .then(response => response.json())
            .then(instances => {
                if (instances && instances.length > 0) {
                    // 清空表格
                    instancesTable.innerHTML = '';
                    
                    // 填充实例数据
                    instances.forEach(instance => {
                        const row = document.createElement('tr');
                        
                        // 添加实例信息
                        row.innerHTML = `
                            <td>${instance.task_instances_id}</td>
                            <td>${instance.start_time_formatted}</td>
                            <td>${instance.end_time_formatted || '进行中'}</td>
                            <td>
                                ${getStatusBadge(instance.status)}
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info view-log" data-instance-id="${instance.task_instances_id}" data-task-name="${instance.task_name}">
                                    <i class="bi bi-file-text"></i> 查看日志
                                </button>
                            </td>
                        `;
                        
                        instancesTable.appendChild(row);
                    });
                    
                    // 添加查看日志事件
                    document.querySelectorAll('.view-log').forEach(button => {
                        button.addEventListener('click', function() {
                            const instanceId = this.getAttribute('data-instance-id');
                            const taskName = this.getAttribute('data-task-name');
                            
                            // 显示任务名称
                            document.getElementById('logTaskName').textContent = `任务: ${taskName} (实例 ID: ${instanceId})`;
                            
                            // 设置刷新按钮的实例ID
                            document.getElementById('refreshLogBtn').setAttribute('data-instance-id', instanceId);
                            
                            // 加载任务日志
                            loadTaskLog(instanceId);
                            
                            // 显示日志模态框
                            new bootstrap.Modal(document.getElementById('taskLogModal')).show();
                        });
                    });
                } else {
                    instancesTable.innerHTML = '<tr><td colspan="5" class="text-center">暂无任务实例记录</td></tr>';
                }
            })
            .catch(error => {
                console.error('加载任务实例失败:', error);
                instancesTable.innerHTML = '<tr><td colspan="5" class="text-center text-danger">加载失败: ' + error.message + '</td></tr>';
            });
        }
        
        // 辅助函数：加载任务日志
        function loadTaskLog(instanceId) {
            const logContent = document.getElementById('logContent');
            const logContentPre = document.getElementById('task-log-content');
            
            // 显示加载中状态 - 根据DOM结构选择正确的元素
            if (logContentPre) {
                logContentPre.textContent = '加载中...';
            } else {
                logContent.textContent = '加载中...';
            }
            
            fetch(`/api/task-instances/${instanceId}/logs`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success' && data.logs && data.logs.length > 0) {
                    const logText = data.logs.join('\n');
                    if (logContentPre) {
                        logContentPre.textContent = logText;
                    } else {
                        logContent.textContent = logText;
                    }
                } else {
                    const emptyText = '没有找到日志记录';
                    if (logContentPre) {
                        logContentPre.textContent = emptyText;
                    } else {
                        logContent.textContent = emptyText;
                    }
                }
            })
            .catch(error => {
                console.error('加载任务日志失败:', error);
                const errorText = '加载日志失败: ' + error.message;
                if (logContentPre) {
                    logContentPre.textContent = errorText;
                } else {
                    logContent.textContent = errorText;
                }
            });
        }
        
        // 辅助函数：获取状态徽章HTML
        function getStatusBadge(status) {
            switch (status) {
                case 'running':
                    return '<span class="badge bg-primary">运行中</span>';
                case 'completed':
                    return '<span class="badge bg-success">已完成</span>';
                case 'failed':
                    return '<span class="badge bg-danger">失败</span>';
                default:
                    return '<span class="badge bg-secondary">未知</span>';
            }
        }
        
        // 辅助函数：显示添加任务模态框中的消息
        function showAddTaskMessage(message, type = 'warning') {
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type} alert-dismissible fade show`;
            messageDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            // 获取添加模态框的消息容器
            const messageContainer = document.getElementById('addTaskModalMessages') || document.querySelector('#addTaskModal .modal-body');
            
            // 清除已有消息
            const existingMessages = messageContainer.querySelectorAll('.alert');
            existingMessages.forEach(msg => msg.remove());
            
            // 添加新消息到容器的顶部
            messageContainer.insertBefore(messageDiv, messageContainer.firstChild);
            
            // 3秒后自动消失
            setTimeout(() => {
                messageDiv.classList.remove('show');
                setTimeout(() => {
                    if (messageDiv.parentNode) {
                        messageDiv.parentNode.removeChild(messageDiv);
                    }
                }, 150);
            }, 3000);
        }
        
        // 辅助函数：显示编辑模态框中的消息
        function showEditMessage(message, type = 'warning') {
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type} alert-dismissible fade show`;
            messageDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            // 获取编辑模态框的消息容器
            const messageContainer = document.getElementById('editTaskModalMessages') || document.querySelector('#editTaskModal .modal-body');
            
            // 清除已有消息
            const existingMessages = messageContainer.querySelectorAll('.alert');
            existingMessages.forEach(msg => msg.remove());
            
            // 添加新消息到容器的顶部
            messageContainer.insertBefore(messageDiv, messageContainer.firstChild);
            
            // 3秒后自动消失
            setTimeout(() => {
                messageDiv.classList.remove('show');
                setTimeout(() => {
                    if (messageDiv.parentNode) {
                        messageDiv.parentNode.removeChild(messageDiv);
                    }
                }, 150);
            }, 3000);
        }

        // 辅助函数：显示全局消息提示
        function showAlert(message, type = 'info') {
            // 创建警告容器
            const alertContainer = document.createElement('div');
            alertContainer.className = 'position-fixed top-0 end-0 p-3';
            alertContainer.style.zIndex = '9999';
            
            // 创建警告元素
            const alertEl = document.createElement('div');
            alertEl.className = `alert alert-${type} alert-dismissible fade show`;
            alertEl.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            // 添加到容器和页面
            alertContainer.appendChild(alertEl);
            document.body.appendChild(alertContainer);
            
            // 3秒后自动关闭
            setTimeout(() => {
                alertEl.classList.remove('show');
                setTimeout(() => {
                    if (alertContainer.parentNode) {
                        document.body.removeChild(alertContainer);
                    }
                }, 150);
            }, 3000);
        }
        
        // 辅助函数：加载任务列表
        function loadTasks() {
            fetch('/api/tasks')
            .then(response => response.json())
            .then(tasks => {
                const tasksTable = document.getElementById('tasks-table');
                
                if (tasks && tasks.length > 0) {
                    // 清空表格并重新填充
                    tasksTable.innerHTML = '';
                    
                    // 使用模板填充任务列表
                    tasks.forEach(task => {
                        // 主行
                        const taskRow = document.createElement('tr');
                        taskRow.className = 'task-row';
                        taskRow.setAttribute('data-task-id', task.id);
                        
                        // 设置行内容
                        taskRow.innerHTML = `
                            <td>${task.id}</td>
                            <td>${task.name}</td>
                            <td>${task.source_connection_name || ''}</td>
                            <td>${task.target_connection_names || ''}</td>
                            <td>
                                ${task.sync_type === 'file_sync' ? '<span class="badge bg-info">文件同步</span>' : ''}
                                ${task.sync_type === 'file_move' ? '<span class="badge bg-primary">文件移动</span>' : ''}
                            </td>
                            <td>${task.created_at || ''}</td>
                            <td>${task.last_run || '从未'}</td>
                            <td>${task.next_run || '未计划'}</td>
                            <td>
                                ${task.status === 'running' ? '<span class="badge bg-primary">运行中</span>' : ''}
                                ${task.status === 'completed' ? '<span class="badge bg-success">已完成</span>' : ''}
                                ${task.status === 'failed' ? '<span class="badge bg-danger">失败</span>' : ''}
                                ${task.status === 'pending' ? '<span class="badge bg-secondary">等待中</span>' : ''}
                            </td>
                            <td>
                                <div class="btn-group">
                                    <button class="btn btn-sm btn-primary run-task" data-task-id="${task.id}">
                                        <i class="bi bi-play-fill"></i>
                                    </button>
                                    <button class="btn btn-sm btn-info edit-task" data-task-id="${task.id}">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-task" data-task-id="${task.id}">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                    <button class="btn btn-sm btn-secondary view-instances" data-task-id="${task.id}" data-task-name="${task.name}">
                                        <i class="bi bi-list-ul"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        
                        // 详情行
                        const detailRow = document.createElement('tr');
                        detailRow.className = 'task-detail-row';
                        detailRow.id = `task-detail-${task.id}`;
                        detailRow.style.display = 'none';
                        
                        // 差异项处理策略文本
                        let diffActionText = '不处理';
                        if (task.sync_diff_action === 'move') diffActionText = '移至回收站';
                        if (task.sync_diff_action === 'delete') diffActionText = '删除';
                        
                        // 设置详情行内容
                        detailRow.innerHTML = `
                            <td colspan="10">
                                <div class="card tech-card mb-0">
                                    <div class="card-body">
                                        <h5 class="card-title">任务详情</h5>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>源路径:</strong> ${task.source_path || '/'}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>目标路径:</strong> ${task.target_path || '/'}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>同步模式:</strong> 
                                                    ${task.sync_type === 'file_sync' ? '文件同步' : ''}
                                                    ${task.sync_type === 'file_move' ? '文件移动' : ''}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>差异项处理:</strong> ${diffActionText}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>排除目录:</strong> ${task.exclude_dirs || '无'}
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>计划:</strong> ${task.schedule || '手动执行'}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>文件过滤:</strong> ${task.file_filter || '无'}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>启用状态:</strong> ${task.enabled !== false ? '启用' : '禁用'}
                                                </div>
                                                <div class="mb-2">
                                                    <strong>目标存储数量:</strong> 
                                                    ${Array.isArray(task.target_connection_ids) ? task.target_connection_ids.length : 1}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        `;
                        
                        // 添加到表格
                        tasksTable.appendChild(taskRow);
                        tasksTable.appendChild(detailRow);
                    });
                    
                    // 为任务行和按钮添加事件
                    attachTaskButtonEvents();
                    console.log('在loadTasks中绑定任务行点击事件');
                    
                    // 再次确保任务行绑定了点击事件
                    const taskRows = document.querySelectorAll('.task-row');
                    taskRows.forEach(row => {
                        // 移除旧事件，防止重复
                        row.removeEventListener('click', taskRowClickHandler);
                        // 添加新事件
                        row.addEventListener('click', taskRowClickHandler);
                        console.log('在loadTasks中为任务行绑定点击事件:', row.getAttribute('data-task-id'));
                    });
                } else {
                    tasksTable.innerHTML = '<tr><td colspan="10" class="text-center">暂无任务</td></tr>';
                }
            })
            .catch(error => {
                console.error('加载任务列表失败:', error);
                document.getElementById('tasks-table').innerHTML = 
                    '<tr><td colspan="10" class="text-center text-danger">加载任务列表失败</td></tr>';
            });
        }
        
        // 为新加载的任务按钮绑定事件
        function attachTaskButtonEvents() {
            // 编辑任务按钮
            document.querySelectorAll('.edit-task').forEach(button => {
                button.addEventListener('click', function() {
                    const taskId = this.getAttribute('data-task-id');
                    
                    // 显示加载状态
                    this.disabled = true;
                    const originalHTML = this.innerHTML;
                    this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                    
                    // 通过API获取任务信息
                    fetch(`/api/tasks/${taskId}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('获取任务信息失败');
                        }
                        return response.json();
                    })
                    .then(task => {
                        // 调试输出任务数据
                        console.log('获取到的任务数据:', task);
                        
                        // 填充表单
                        document.getElementById('editTaskId').value = task.id;
                        document.getElementById('editTaskName').value = task.name;
                        
                        // 设置源路径和目标路径
                        document.getElementById('editSourcePath').value = task.source_path || '/';
                        document.getElementById('editTargetPath').value = task.target_path || '/';
                        document.getElementById('editSyncType').value = task.sync_type || 'file_sync';
                        document.getElementById('editSyncDiffAction').value = task.sync_diff_action || 'none';
                        document.getElementById('editSchedule').value = task.schedule || '';
                        document.getElementById('editFileFilter').value = task.file_filter || '';
                        
                        // 最小/最大文件大小
                        document.getElementById('editSizeMin').value = task.size_min != null ? task.size_min : '';
                        document.getElementById('editSizeMax').value = task.size_max != null ? task.size_max : '';
                        document.getElementById('editExcludeDirs').value = task.exclude_dirs || '';
                        document.getElementById('editTaskEnabled').checked = task.enabled !== false;
                        
                        // 先加载所有连接，然后选择任务使用的连接并加载存储列表
                        loadConnectionsForEdit(task);
                        
                        // 显示编辑模态框
                        new bootstrap.Modal(document.getElementById('editTaskModal')).show();
                    })
                    .catch(error => {
                        console.error('获取任务信息失败:', error);
                        showAlert('获取任务信息失败: ' + error.message, 'danger');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = originalHTML;
                    });
                });
            });
            
            // 删除按钮事件
            document.querySelectorAll('.delete-task').forEach(button => {
                button.addEventListener('click', function() {
                    const taskId = this.getAttribute('data-task-id');
                    document.getElementById('deleteTaskId').value = taskId;
                    
                    // 重新绑定确认删除按钮的事件处理函数
                    const confirmBtn = document.getElementById('confirmDeleteBtn');
                    // 移除之前可能存在的事件监听器
                    const newConfirmBtn = confirmBtn.cloneNode(true);
                    confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
                    
                    // 为新按钮添加事件监听器
                    newConfirmBtn.addEventListener('click', function() {
                        deleteTask(taskId, this);
                    });
                    
                    new bootstrap.Modal(document.getElementById('confirmDeleteModal')).show();
                });
            });
            
            // 运行任务按钮
            document.querySelectorAll('.run-task').forEach(button => {
                button.addEventListener('click', function() {
                    const taskId = this.getAttribute('data-task-id');
                    
                    // 显示加载状态
                    const originalHTML = this.innerHTML;
                    this.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                    this.disabled = true;
                    
                    // 发送AJAX请求运行任务
                    fetch(`/api/tasks/${taskId}/run`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应错误');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.status === 'success') {
                            // 显示任务运行结果
                            if (data.instance_id) {
                                // 如果返回了实例ID，提示查看日志
                                const result = confirm(`任务 ${taskId} 已开始运行，是否查看执行日志？`);
                                if (result) {
                                    // 显示任务名称
                                    const taskName = this.closest('tr').querySelector('td:nth-child(2)').textContent;
                                    document.getElementById('logTaskName').textContent = `任务: ${taskName} (实例 ID: ${data.instance_id})`;
                                    
                                    // 设置刷新按钮的实例ID
                                    document.getElementById('refreshLogBtn').setAttribute('data-instance-id', data.instance_id);
                                    
                                    // 加载任务日志
                                    loadTaskLog(data.instance_id);
                                    
                                    // 显示日志模态框
                                    new bootstrap.Modal(document.getElementById('taskLogModal')).show();
                                }
                            } else {
                                showAlert(`任务 ${taskId} 已开始运行`, 'success');
                            }
                            // 刷新任务列表而不是整个页面
                            loadTasks();
                            
                            // 重新加载调度器以更新任务计划
                            setTimeout(() => {
                                fetch('/api/scheduler/reload', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    }
                                })
                                .then(response => response.json())
                                .then(result => {
                                    console.log('调度器已重载:', result);
                                    // 在调度器重载后再次刷新，确保下次运行时间更新
                                    setTimeout(() => {
                                        loadTasks();
                                    }, 1000);
                                })
                                .catch(err => {
                                    console.error('调度器重载失败:', err);
                                });
                            }, 500);
                        } else {
                            throw new Error(data.message || '运行失败');
                        }
                    })
                    .catch(error => {
                        console.error('运行任务失败:', error);
                        showAlert('运行任务失败: ' + error.message, 'danger');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.innerHTML = originalHTML;
                        this.disabled = false;
                    });
                });
            });
            
            // 查看任务实例按钮
            document.querySelectorAll('.view-instances').forEach(button => {
                button.addEventListener('click', function() {
                    const taskId = this.getAttribute('data-task-id');
                    const taskName = this.getAttribute('data-task-name');
                    
                    // 显示任务名称
                    document.getElementById('instancesTaskName').textContent = `任务: ${taskName} (ID: ${taskId})`;
                    
                    // 加载任务实例列表
                    loadTaskInstances(taskId);
                    
                    // 显示模态框
                    new bootstrap.Modal(document.getElementById('taskInstancesModal')).show();
                });
            });
            
            // 为任务行绑定点击事件
            console.log('在attachTaskButtonEvents中为任务行绑定点击事件');
            const taskRows = document.querySelectorAll('.task-row');
            taskRows.forEach(row => {
                // 移除旧事件，防止重复
                row.removeEventListener('click', taskRowClickHandler);
                // 添加新事件
                row.addEventListener('click', taskRowClickHandler);
                console.log('已为任务行绑定点击事件:', row.getAttribute('data-task-id'));
            });
        }
        
        // 为任务行添加点击展开/收起功能
        function attachTaskRowEvents() {
            console.log('开始绑定任务行点击事件...');
            // 获取所有任务行
            const taskRows = document.querySelectorAll('.task-row');
            console.log(`找到 ${taskRows.length} 个任务行`);
            
            // 为所有任务行添加点击事件
            taskRows.forEach(row => {
                row.addEventListener('click', function(event) {
                    console.log('任务行被点击:', this.getAttribute('data-task-id'));
                    // 如果点击的是按钮，不处理展开/收起
                    if (event.target.tagName === 'BUTTON' || 
                        event.target.closest('button') || 
                        event.target.tagName === 'I' ||
                        event.target.closest('.btn-group')) {
                        console.log('点击了按钮区域，忽略展开/收起');
                        return;
                    }
                    
                    // 获取任务ID
                    const taskId = this.getAttribute('data-task-id');
                    console.log('准备切换详情显示，任务ID:', taskId);
                    const detailRow = document.getElementById(`task-detail-${taskId}`);
                    if (!detailRow) {
                        console.error(`找不到详情行 task-detail-${taskId}`);
                        return;
                    }
                    
                    // 切换详情行的显示状态
                    if (detailRow.style.display === 'none' || !detailRow.style.display) {
                        console.log('显示详情行');
                        // 关闭其他打开的详情行
                        document.querySelectorAll('.task-detail-row').forEach(row => {
                            if (row.id !== `task-detail-${taskId}`) {
                                row.style.display = 'none';
                                // 移除其他行的活动状态
                                const otherId = row.id.replace('task-detail-', '');
                                const otherRow = document.querySelector(`.task-row[data-task-id="${otherId}"]`);
                                if (otherRow) otherRow.classList.remove('active-task-row');
                            }
                        });
                        
                        // 显示当前详情行
                        detailRow.style.display = 'table-row';
                        this.classList.add('active-task-row');
                    } else {
                        console.log('隐藏详情行');
                        // 隐藏当前详情行
                        detailRow.style.display = 'none';
                        this.classList.remove('active-task-row');
                    }
                });
                console.log('已为任务行绑定点击事件:', row.getAttribute('data-task-id'));
            });
            
            // 阻止详情行的点击事件冒泡
            document.querySelectorAll('.task-detail-row').forEach(row => {
                row.addEventListener('click', function(event) {
                    event.stopPropagation();
                });
                console.log('已阻止详情行的点击事件冒泡:', row.id);
            });
        }
        
        // 将删除任务的逻辑提取到一个单独的函数
        function deleteTask(taskId, buttonElement) {
            // 禁用按钮，显示加载状态
            buttonElement.disabled = true;
            buttonElement.innerHTML = '<i class="bi bi-hourglass-split"></i> 删除中...';
            
            // 发送AJAX请求删除任务
            fetch(`/api/tasks/${taskId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    // 显示成功消息
                    showAlert(`任务 ${taskId} 已删除`, 'success');
                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('confirmDeleteModal')).hide();
                    // 刷新任务列表
                    loadTasks();
                } else {
                    throw new Error(data.message || '删除失败');
                }
            })
            .catch(error => {
                console.error('删除任务失败:', error);
                showAlert('删除任务失败: ' + error.message, 'danger');
            })
            .finally(() => {
                // 恢复按钮状态
                buttonElement.disabled = false;
                buttonElement.innerHTML = '确认删除';
            });
        }
        
        // 辅助函数：显示添加任务模态框中的消息
        function showAddTaskMessage(message, type = 'warning') {
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type} alert-dismissible fade show`;
            messageDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            // 获取添加模态框的消息容器
            const messageContainer = document.getElementById('addTaskModalMessages') || document.querySelector('#addTaskModal .modal-body');
            
            // 清除已有消息
            const existingMessages = messageContainer.querySelectorAll('.alert');
            existingMessages.forEach(msg => msg.remove());
            
            // 添加新消息到容器的顶部
            messageContainer.insertBefore(messageDiv, messageContainer.firstChild);
            
            // 3秒后自动消失
            setTimeout(() => {
                messageDiv.classList.remove('show');
                setTimeout(() => {
                    if (messageDiv.parentNode) {
                        messageDiv.parentNode.removeChild(messageDiv);
                    }
                }, 150);
            }, 3000);
        }
    });
</script>
{% endblock %}